package com.igeek.boot.service;

import com.igeek.boot.constant.RedisMessageConstant;
import com.igeek.boot.result.Result;
import com.igeek.boot.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

/**
 * @Author fengqq
 * @Description TODO
 * @Date 2024/9/5  9:33
 */

@Service
public class SmsService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    public Result sendLogin(String phone) {

        if(StringUtils.hasLength(phone)){
            //1.1分钟内不能重复发送
            if(stringRedisTemplate.opsForValue().get(phone+"_"+RedisMessageConstant.SENDTYPE_LOGIN)!=null){
                return new Result(500,"发送失败，一分钟内不能重复发送验证码");
            }

            //2.生成随机验证码
            String code = ValidateCodeUtils.generateValidateCode4String(4);

            //3.1存储1分钟有效的验证码 用于避免重复发送 18115161666_001
            //3.2存储5分钟有效的验证码 用于登录业务    18115161666_001_code
            stringRedisTemplate.opsForValue().set(phone+"_"+ RedisMessageConstant.SENDTYPE_LOGIN,code,1, TimeUnit.MINUTES);
            stringRedisTemplate.opsForValue().set(phone+"_"+ RedisMessageConstant.SENDTYPE_LOGIN+"_"+code,code,5, TimeUnit.MINUTES);
            return new Result(200,"发送成功",code);
        }
        return new Result(500,"发送失败!没有获取到手机号");
    }
}
